package com.example.guohuan.filelocker;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    MyDbHelper myDbHelper;
    SQLiteDatabase mDb;
    Cursor dbCursor;

    // 要申请的权限  READ_PROFILE没有
    private final String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.READ_CONTACTS};

    /**
     * 开始提交请求权限
     */
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 8);
    }

    /**
     * 用户权限 申请 的回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    //如果没有获取权限，那么可以提示用户去设置界面--->应用权限开启权限
                } else {
                    //获取权限成功提示，可以不要
                    Toast toast = Toast.makeText(this, "获取权限成功", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int n1 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]);
            int n2 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]);
            int n3 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]);
            int n4 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]);
            int n5 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]);
            int n6 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]);
            int n7 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[6]);
            int n8 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[7]);
            int n9 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[8]);
            int n10 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[9]);
            int n11 = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[10]);
            // 权限是否已经 授权 GRANTED---授权 DINIED---拒绝
            if (n1 != PackageManager.PERMISSION_GRANTED ||
                    n2!= PackageManager.PERMISSION_GRANTED ||
                    n3 != PackageManager.PERMISSION_GRANTED ||
                    n4 != PackageManager.PERMISSION_GRANTED ||
                    n5 != PackageManager.PERMISSION_GRANTED ||
                    n6 != PackageManager.PERMISSION_GRANTED ||
                    n7 != PackageManager.PERMISSION_GRANTED ||
                    n8 != PackageManager.PERMISSION_GRANTED ||
                    n9 != PackageManager.PERMISSION_GRANTED ||
                    n10 != PackageManager.PERMISSION_GRANTED ||
                    n11 != PackageManager.PERMISSION_GRANTED
            ) {
                // 如果没有授予该权限，就去提示用户请求
                startRequestPermission();
            }}



        super.onCreate(savedInstanceState);
        myDbHelper = new MyDbHelper(MainActivity.this);
        mDb = myDbHelper.getWritableDatabase();
        dbCursor = mDb.rawQuery("SELECT * FROM " + MyDbHelper.LOGIN_TABLE_NAME, null);

        //初次登录验证两次密码
        if (!dbCursor.moveToFirst()) {
            setContentView(R.layout.activity_main_nopass);


            final EditText password1 = (EditText) findViewById(R.id.newPass_editText);
            final EditText password2 = (EditText) findViewById(R.id.newPassC_editText);
            Button signUp = (Button) findViewById(R.id.signUp_button);

            signUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String p1 = password1.getText().toString();
                    String p2 = password2.getText().toString();

                    if(p1.length()!=0&&p2.length()!=0){
                        if(p1.matches(p2)){
                            ContentValues newValues = new ContentValues();
                            newValues.put(MyDbHelper.LOGIN_COL_PASSWORD, p1);
                            mDb.insert(
                                    MyDbHelper.LOGIN_TABLE_NAME,
                                    null,
                                    newValues
                            );
                            Toast.makeText(MainActivity.this,"password created",Toast.LENGTH_SHORT).show();
                            Intent newIntent = new Intent(MainActivity.this,CmenuActivity.class);
                            startActivity(newIntent);
                        }
                        else{
                            Toast.makeText(MainActivity.this,"password doesn't match",Toast.LENGTH_SHORT).show();
                        }
                    }
                    else{
                        Toast.makeText(MainActivity.this,"Please enter both passwords",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        else {

            //登录验证
            setContentView(R.layout.activity_main_pass);
            final EditText password = (EditText) findViewById(R.id.pass_editText);
            Button login = (Button) findViewById(R.id.login_button);

            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String p = password.getText().toString();
                    String[] allColumns = new String[]{"_id", MyDbHelper.LOGIN_COL_PASSWORD};
                    dbCursor = mDb.query(true,
                            MyDbHelper.LOGIN_TABLE_NAME, allColumns,
                            null, null, MyDbHelper.LOGIN_COL_PASSWORD, null, null,null);
                    if (dbCursor != null)
                        dbCursor.moveToFirst();

                    if (dbCursor.moveToFirst()){
                        String data = dbCursor.getString(dbCursor.getColumnIndex(MyDbHelper.LOGIN_COL_PASSWORD));
                        if(data.matches(p)){
                            Toast.makeText(MainActivity.this,"Login successful",Toast.LENGTH_SHORT).show();
                            Intent newIntent = new Intent(MainActivity.this,CmenuActivity.class);
                            startActivity(newIntent);
                        }
                        else{
                            Toast.makeText(MainActivity.this,"Password incorrect",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

        }
    }

    //此方法用于初始化菜单，其中menu参数就是即将要显示的Menu实例。
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;//返回true则显示该menu,false 则不显示
    }

//    菜单项监听:
//    只要菜单中的菜单项被点击，都会触发onOptionsItemSelected(MenuItem item)
//    item参数即为被点击的菜单项，那么需要在此方法内判断哪个Item被点击了，从而实现不同的操作。
//    对于两种不同的添加菜单方法，判断的方法有一点区别，但本质是一样的。
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(MainActivity.this,SettingActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
